package com.mot.j2me.midlets;																		

/*
 * A free J2ME sample program to demonstrate
 * a SIMPLE LOGIN SCREEN TO LOGIN TO A HTTP SERVER 
 * FROM A J2ME phone
 *
 * @author William Alexander
 * code modified by @author Hitesh Ubharani
 * free for use as long as this comment is included in
 * in the program as it is
 * More Free Java programs available for download 
 * at http://www.java-samples.com
 *
 */
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;  

import java.io.*;

import javax.microedition.io.*;

public class LDPrivacyPref extends MIDlet implements CommandListener {
    
	TextField Pin=null;
	ChoiceGroup choiceMenu = new ChoiceGroup("Mlbs Demo", Choice.EXCLUSIVE);
    TextField Location=null;
	Form  mainscreen, menu;
	TextBox t = null;
	StringItem si = new StringItem("","");
	StringBuffer b = new StringBuffer();
    Display myDisplay = null;
    private Command okCommand = new Command("OK", Command.OK, 1);
    private Command exitCommand = new Command("Exit", Command.EXIT, 0);
    private Command backCommand = new Command("Back", Command.BACK, 1);

    public LDPrivacyPref() {        

    myDisplay = Display.getDisplay(this);
    choiceMenu.append("Don't Share Location", null);
    choiceMenu.append("Share Location", null);
    menu=new Form("Mlbs Demo");
    menu.addCommand(exitCommand);
    menu.addCommand(okCommand);
    menu.append(choiceMenu);
    menu.setCommandListener(this);
    myDisplay.setCurrent(menu);
    mainscreen=new Form(" ");
	

    }

    public void startApp() throws MIDletStateChangeException { 
    }

    public void pauseApp() {
    }


  
    protected void destroyApp(boolean unconditional)
            throws MIDletStateChangeException {
    }

    public void displayString(String string) {
		// form.append(si);
		si.setText(string);

	}

    public void commandAction(Command c, Displayable d) {
        
	    if ((c == okCommand)) {
			
			    
	          
	        
	        mainscreen.deleteAll();
	        si.setText("Loading..");
			mainscreen.append(si);
			mainscreen.addCommand(backCommand);
			mainscreen.addCommand(exitCommand);
			mainscreen.setCommandListener(this);
			myDisplay.setCurrent(mainscreen);
			Ret ret = new Ret(this, choiceMenu.getSelectedIndex());
			ret.start();
	            
				
			
		}
	   
	     if (c == backCommand)  {
	    	myDisplay.setCurrent(menu);
		}
		
	    if (c == exitCommand) {
	    	try {
                destroyApp(true);
                notifyDestroyed();
            } catch (MIDletStateChangeException e) {
                e.printStackTrace();
            }
            
		}
	}
        
   
} 




class Ret extends Thread {
    
	private LDPrivacyPref midlet;
    String caching ="enable";
	private int selectedIndex;

     public Ret(LDPrivacyPref cache, int selectedIndex ){
        
    	 /**
          * Constructor
          *
          * EFFECTS: Initialise the server and store midlet information
          * @param midlet The main application midlet
          * @param server Forecast Server URL
          */
    	 
        this.midlet = cache;
        this.selectedIndex = selectedIndex;
        
        
    }


    public void run(){
            /**
            * Entry point of the thread
            * EFFECTS: call to connect() method
            */
        
    	try {
    		                  
        	   loadPage(selectedIndex);
           
               
            } catch (Exception ex){
               ex.printStackTrace();

               
            }
            
        }
    
   
    public void loadPage(int selectedIndex) {
		long endTime, startTime = System.currentTimeMillis();
		long time;
		String privacy;
		
		if(selectedIndex == 0){
			privacy = "disable";
		}
		else{
			privacy = "enable";
		}
		String param1 = "query=testPrivacy";
		param1+="&privacy="+privacy;
		param1+="&IMEI=0123456789";
		String str = loadURL(param1);
		// t = new TextBox("Reply",b.toString(),1024,0);
		midlet.b.setLength(0);
		midlet.b.append(str);
		midlet.mainscreen.append(midlet.b.toString());
		endTime = System.currentTimeMillis();
		time = endTime - startTime;
		midlet.displayString("Load time is " + Long.toString(time) + "ms");
		midlet.myDisplay.setCurrent(midlet.mainscreen);
	}

	public String loadURL(String query){
		String URL   = "http://mlbs.no-ip.org:8080/MLBSWebApp/MlbsServlet"+"?"+query;
    	URL = urlEncoder(URL);
    	System.out.println("URL:"+URL);
    
		HttpConnection c = null;
		InputStream is = null;
		try {
		  System.out.println("In XXXX .....\n\n");
		  c = (HttpConnection)Connector.open(URL);	
		  c.setRequestMethod(HttpConnection.GET);
		  is = c.openInputStream();
		  
		  ///////////
		  if (c.getResponseCode() == HttpConnection.HTTP_OK)
		  {
		        int length = (int) c.getLength();
		        String str;
		        if (length != -1){
		          byte servletData[] = new byte[length];
		          is.read(servletData);
		          str = new String(servletData);
		          System.out.println("server response:"+str);
		          return str;
		        }else  // Length not available...
		        {
		          ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
		          
		          int ch;
		          while ((ch = is.read()) != -1){
		            bStrm.write(ch);
		          }
		          str = new String(bStrm.toByteArray());
		          bStrm.close();
		        }
		        System.out.println("server response2:"+str);
		        return str;
		   
		  }
		  //////////
		}catch (Exception e) {
			// TODO: handle exception
		}finally {
			          try {
						is.close();
						c.close();
					} catch (Exception e) {
						
					}
			  }
		return null;
		} 
	
 	public static String urlEncoder(String s) {
 		if (s == null)
 			return s;
 		s=s.replace(' ' , '+');
 		return s;
 	}
	
}